package com.jhws.business.comm.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.jhws.business.card.bo.CardConstant;
import com.jhws.business.comm.bo.CommUpdateData;
import com.jhws.business.comm.bo.TblCommDimBo;
import com.jhws.business.comm.service.ITblCommDimService;
import com.jhws.business.comm.service.ITblAreaDimService;
import com.jhws.business.comm.service.ITblBuildingDimService;
import com.jhws.business.customer.bo.SdkCustomers;
import com.jhws.common.base.bo.JsonRespData;
import com.jhws.business.customer.service.SdkCustService;
import com.jhws.core.dataUpdate.service.DataUpdateService;
import com.jhws.core.push.PushXinGe;
import com.jhws.sys.appUser.service.ITblSipAcountDimService;
import com.jhws.sys.user.service.ITblUserDimService;
import com.jhws.util.DateUtil;
import com.jhws.util.ObjectUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.jhws.common.base.bo.Global;
import com.jhws.common.PropertiesReader;
import com.jhws.util.commUtil;

@Controller
@RequestMapping("/comm")
public class CommCtrl {
    @Resource
    protected ITblSipAcountDimService ITblSipAcountDimService;
    @Resource
    protected ITblCommDimService ITblCommDimService;
    @Resource
    protected ITblAreaDimService ITblAreaDimService;
    @Resource
    protected com.jhws.sys.menu.service.ITblMenuDimService ITblMenuDimService;
    @Resource
    protected ITblBuildingDimService ITblBuildingDimService;
    @Resource
    private SdkCustService customerService;
    @Resource
    private RedisTemplate stringTemplate;
    @Resource
    private DataUpdateService dataUpdateService;
    @Resource
    private ITblUserDimService IUserService;

    @RequestMapping("save.x")
    @ResponseBody
    public JsonRespData save(TblCommDimBo comm, boolean localServer) throws java.lang.Exception {
        Boolean updatePush = false;
        TblCommDimBo bo = ITblCommDimService.findTblCommDimById(comm.getCommCode());
        boolean isNew = false;
        if(bo == null){
            isNew = true;
            bo = new TblCommDimBo();
        }

        if(!isNew && !comm.getPermissionFace().equals(bo.getPermissionFace())){
            updatePush = true;
        }

        if(!isNew && !comm.getPermissionCardPhoto().equals(bo.getPermissionCardPhoto())){
            updatePush = true;
        }

		/* 添加本地服务器sip账号 */
        String localServer_useranme = comm.getCommCode() + "_" + "LocalServer";
        if (localServer) {
            if (ITblSipAcountDimService.isUserExist(localServer_useranme) == null)
                ITblSipAcountDimService.addSipAccount(localServer_useranme, "Jh_lc_pwd", "local_srv", false);
        } else {
            if (ITblSipAcountDimService.isUserExist(localServer_useranme) != null)
                ITblSipAcountDimService.remove(localServer_useranme);
        }

		/* 添加pstn服务器sip账号 */
        String pstnServer_useranme = comm.getCommCode() + "_" + "PstnServer";
        /* 只有选择了本小区,才会创建pstn账号 */
        if (StringUtils.isNotEmpty(comm.getPstnComm()) && comm.getPstnComm().equals(comm.getCommCode())) {
            if (ITblSipAcountDimService.isUserExist(pstnServer_useranme) == null)
                ITblSipAcountDimService.addSipAccount(pstnServer_useranme, "Jh_"+comm.getCommCode()+"_pstn_pwd", "pstn_srv", false);
        } else {
            if (ITblSipAcountDimService.isUserExist(pstnServer_useranme) != null)
                ITblSipAcountDimService.remove(pstnServer_useranme);
        }

        /* 不管是新增还是修改,都清空下信鸽APPkey的缓存 */
        if(StringUtils.isNotEmpty(PropertiesReader.getProperty("basePlatform"))){
            HashOperations hashOperations = stringTemplate.opsForHash();
            hashOperations.delete(PushXinGe.REDIS_XINGE_APPID,comm.getCommCode());
        }

        if (isNew) {
            comm.setCommPassword(String.valueOf((int) ((Math.random() * 9 + 1) * 100000)));
            comm.setCommSoftVersion(Global.COMM_SOFT_VERSION);
            comm.setGateDevAliasName("");
            comm.setCreateTime(DateUtil.getTimeNowFmtDay());
        }

        Date timeStamp = new Date();
        ObjectUtils.copyPropertiesIgnoreNull(comm,bo);
        ITblCommDimService.save(bo);
        if(updatePush){
            dataUpdateService.pushAndUpdate(timeStamp.getTime(), CommUpdateData.COMM_INFO,bo.getCommCode(),false,false,"小区信息更新","");
        }
        return new JsonRespData("",1,"添加小区信息成功！");
    }

    @RequestMapping("remove.x")
    @ResponseBody
    public JsonRespData remove(String commCode) throws java.lang.Exception {

        this.ITblBuildingDimService.removeBuildingByComm(commCode);
        this.ITblAreaDimService.removeDim(null, commCode);
        this.ITblCommDimService.removeGrgDim(commCode);

		/* 删除SIP账号：管理机账号 */
        this.ITblSipAcountDimService.removeByComm(commCode);

        return new JsonRespData("",1,"");
    }

    @RequestMapping("findCommListPage.x")
    @ResponseBody
    public Object findCommListPage(@RequestParam Map param) {
        return ITblCommDimService.findCommListPage(param);
    }

    @RequestMapping("findCommList.x")
    @ResponseBody
    public Object findCommList(Map param) throws Exception {
        return new JsonRespData("findCommList", 1, ITblCommDimService.findCommList(param));
    }

    @RequestMapping("getCommInfo.x")
    @ResponseBody
    public JsonRespData getCommInfo(@RequestParam Map params) throws Exception {
        Map infos = new HashMap();
        if ("allowPstn".equals(params.get("type"))) {
            String comm = (String) params.get("commCode");
            TblCommDimBo bo = ITblCommDimService.findTblCommDimByCommCode(comm);
            return new JsonRespData("getCommInfo", 1, StringUtils.isNotEmpty(bo.getPstnComm()));
        }
        if(params.get("validCommCode") != null){
            String commCode = "";
            if (!PropertiesReader.getProperty("isLanMode").equals("true")) {

                List<TblCommDimBo> list = ITblCommDimService.findTblCommDimByWhere("");
                if (null != list && !list.isEmpty()) {
                    TblCommDimBo tblCommDimBo = list.get(list.size() - 1);
                    String commCodeStr = tblCommDimBo.getCommCode();
                    int intCode = Integer.valueOf(commCodeStr) + 1;
                    commCode= commUtil.appendZero(intCode + "");
                } else {
                    commCode = "0001";
                }
            }

            infos.put("validCommCode",commCode);
        }

        if(params.get("clientList") != null){
            List<SdkCustomers> customers = customerService.queryCustomerList();
            infos.put("clientList",customers);
        }

        if(params.get("commInfo") != null){
            String commCode = MapUtils.getString(params,"commInfo");
            infos.put("commInfo",ITblCommDimService.findTblCommDimById(commCode));
        }

        if(params.get("localServer") != null){
            String commCode = MapUtils.getString(params,"localServer");
            String localServer_useranme = commCode + "_" + "LocalServer";
            if (ITblSipAcountDimService.isUserExist(localServer_useranme) != null)
                infos.put("localServer",true);
        }

        if(params.get("cardVendors") != null){
            infos.put("cardVendors", CardConstant.cardVendors());
        }

        return new JsonRespData("getCommInfo", 1, infos);
    }

    /*
        设置围墙机别名,存入小区表中

        @param:commCode  小区编号
        @param:gateAliasName  前端传入的别名,以逗号分开
     */
    @RequestMapping("setGateAliasName.x")
    @ResponseBody
    public JsonRespData setGateAliasName(String commCode,String gateAliasName) throws Exception{
        if(StringUtils.isNotEmpty(gateAliasName) && StringUtils.isNotEmpty(commCode)){
            TblCommDimBo comm = ITblCommDimService.findTblCommDimById(commCode);
            if(comm != null) {
                comm.setGateDevAliasName(gateAliasName);
                ITblCommDimService.save(comm);
            }
        }
        return new JsonRespData("",1,"设置成功!");
    }

}
